package com.leon.androidcoursedesign.ui.fragments.loginFragments;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import androidx.navigation.Navigation;

import com.leon.androidcoursedesign.R;
import com.leon.androidcoursedesign.ui.activitys.HomeActivity;
import com.leon.androidcoursedesign.ui.fragments.baseFragment.BaseFragment;
import com.leon.androidcoursedesign.ui.fragments.baseFragment.BindingUtils;
import com.leon.androidcoursedesign.utils.dataBaseUtils.AccountInfoUtils;
import com.leon.androidcoursedesign.utils.dataBaseUtils.SQLiteHelperFactory;
import com.leon.androidcoursedesign.utils.dataBaseUtils.Tables;

public class LoginFragment extends BaseFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private EditText
            main_fragment_editText_id,
            main_fragment_editText_pwd;

    private CheckBox
            main_fragment_checkBox_remPwd,
            main_fragment_checkBox_auto;

    private SharedPreferences preferenceValues;
    private AccountInfoUtils accountInfoUtils;

    private String tempId;
    private String tempPwd;

    private boolean isRememberAccount;
    private boolean isAutoLogin;

    @Override
    public int setLayout() {
        return R.layout.login_fragment;
    }

    @Override
    public void init() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            tempId = arguments.getString("uid");
            tempPwd = arguments.getString("pwd");
        } else {
            SharedPreferences preferenceValues = context.getSharedPreferences("preferenceValues", Activity.MODE_PRIVATE);

            isRememberAccount = preferenceValues.getBoolean("isRememberAccount", false);
            isAutoLogin = preferenceValues.getBoolean("isAutoLogin", false);

            tempId = preferenceValues.getString("tempId", "");
            tempPwd = preferenceValues.getString("tempPwd", "");
        }

        // 校验账户
        boolean state = verifyAccount(tempId, tempPwd);
        if (isRememberAccount) {
            if (!state) {
                Toast.makeText(context, "登录失败，请重新输入账号及密码", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        if (isAutoLogin) {
            if (!state) {
                Toast.makeText(context, "登录失败，请重新输入账号及密码", Toast.LENGTH_SHORT).show();
            } else {
                SharedPreferences.Editor editorOne = context.getSharedPreferences("preferenceValues", Activity.MODE_PRIVATE).edit();
                editorOne.putString("operationId", tempId).apply();

                //直接进入主界面
                Intent intent = new Intent(context, HomeActivity.class);
                startActivity(intent);
                getActivity().finish();
            }
        }
    }

    @Override
    public void initView(BindingUtils bindingUtils) {
        bindingUtils
                .setOnCheckedChangeListener(R.id.main_fragment_checkBox_remPwd, this)
                .setOnCheckedChangeListener(R.id.main_fragment_checkBox_auto, this);

        bindingUtils
                .setOnClickListener(R.id.main_fragment_button_login, this)
                .setOnClickListener(R.id.main_fragment_register, this);

        main_fragment_editText_id = findView(R.id.main_fragment_editText_id);
        main_fragment_editText_pwd = findView(R.id.main_fragment_editText_pwd);

        if (isRememberAccount) {
            if (tempId != null && tempPwd != null) {
                main_fragment_editText_id.setText(tempId);
                main_fragment_editText_pwd.setText(tempPwd);
            }
        }

        main_fragment_checkBox_remPwd = findView(R.id.main_fragment_checkBox_remPwd);
        main_fragment_checkBox_remPwd.setOnCheckedChangeListener(this);

        main_fragment_checkBox_auto = findView(R.id.main_fragment_checkBox_auto);
        main_fragment_checkBox_auto.setOnCheckedChangeListener(this);
    }

    @Override
    public void initValues() {
        if (tempId != null && tempPwd != null) {
            main_fragment_editText_id.setText(tempId);
            main_fragment_editText_pwd.setText(tempPwd);
        }

        preferenceValues = context.getSharedPreferences("preferenceValues", Activity.MODE_PRIVATE);

        boolean isRememberAccount = preferenceValues.getBoolean("isRememberAccount", false);
        boolean isAutoLogin = preferenceValues.getBoolean("isAutoLogin", false);

        main_fragment_checkBox_remPwd.setChecked(isRememberAccount);
        main_fragment_checkBox_auto.setChecked(isAutoLogin);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_fragment_register:
                Navigation.findNavController(view).navigate(R.id.action_mainFragment_to_registerFragment);
                break;
            case R.id.main_fragment_button_login:
                String id = main_fragment_editText_id.getText().toString();
                String pwd = main_fragment_editText_pwd.getText().toString();

                if (id.equals("") || pwd.equals("")) {
                    Toast.makeText(context, "请将账号或密码填写完整", Toast.LENGTH_SHORT).show();
                    break;
                }

                //查看账户是否存在
                boolean accountState = verifyAccount(id, pwd);

                if (!accountState) {
                    Toast.makeText(context, "该账户还未注册或密码错误", Toast.LENGTH_SHORT).show();
                    break;
                } else {
                    SharedPreferences.Editor editorOne = preferenceValues.edit();
                    editorOne.putString("operationId", main_fragment_editText_id.getText().toString()).apply();

                    Intent intent = new Intent(context, HomeActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.main_fragment_checkBox_remPwd:
                SharedPreferences.Editor editorOne = preferenceValues.edit();
                editorOne.putBoolean("isRememberAccount", isChecked);
                editorOne.putString("tempId", main_fragment_editText_id.getText().toString());
                editorOne.putString("tempPwd", main_fragment_editText_pwd.getText().toString());
                editorOne.apply();

                break;
            case R.id.main_fragment_checkBox_auto:
                SharedPreferences.Editor editorTwo = preferenceValues.edit();
                editorTwo.putBoolean("isAutoLogin", isChecked).apply();

                break;
            default:
                break;
        }
    }

    /**
     * 校验账户存在状态
     *
     * @param id    用户ID
     * @param pwd   用户PWD
     * @return  返回用户是否存在
     */
    private boolean verifyAccount(String id, String pwd) {
        if (accountInfoUtils == null) {
            SQLiteHelperFactory sqLiteHelperFactory = new SQLiteHelperFactory(context, Tables.AccountInfo);
            accountInfoUtils = (AccountInfoUtils) sqLiteHelperFactory.getInstance();
        }

        return accountInfoUtils.queryUser(id, pwd);
    }

    @Override
    public void onDestroy() {
        accountInfoUtils.close();
        super.onDestroy();
    }
}